package com.dandandog.framework.faces.aspect;

import cn.hutool.core.util.StrUtil;
import com.dandandog.framework.common.utils.MessageUtil;
import com.dandandog.framework.faces.annotation.MessageRequired;
import com.dandandog.framework.faces.config.properties.MessageProperties;
import com.dandandog.framework.faces.exception.MessageResolvableException;
import com.dandandog.framework.faces.utils.FacesMessageUtils;
import lombok.AllArgsConstructor;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.springframework.boot.context.properties.EnableConfigurationProperties;

import javax.faces.application.FacesMessage;
import java.util.Objects;

/**
 * @author JohnnyLiu
 */
@AllArgsConstructor
@EnableConfigurationProperties(MessageProperties.class)
public abstract class AbstractMessageAspect implements INotice {

    private final MessageProperties properties;

    @Around("@annotation(messageRequired)")
    public Object showMessage(ProceedingJoinPoint joinPoint, MessageRequired messageRequired) throws Throwable {
        NoticeTarget target = new NoticeTarget();
        try {
            Object result = joinPoint.proceed();
            target = defaultSuccess(messageRequired, FacesMessage.SEVERITY_INFO);
            return result;
        } catch (Exception e) {
            target = defaultSuccess(messageRequired, FacesMessage.SEVERITY_ERROR);
            if (e instanceof MessageResolvableException) {
                MessageResolvableException exception = (MessageResolvableException) e;
                target.setDetail(MessageUtil.getMessageSource(exception.getErrorCode()));
            }
            if (true) {
                //throw new FacesException(e.getMessage());
            }
        } finally {
            FacesMessageUtils.show(target);
        }
        return null;
    }


    private NoticeTarget defaultSuccess(MessageRequired messageRequired, FacesMessage.Severity severity) {
        String prefix = properties.getCodePrefix();
        String messageTitle = properties.getTitle();
        String messageContent;
        String clientId;
        if (Objects.equals(severity, FacesMessage.SEVERITY_INFO)) {
            messageContent = messageRequired.type().getSuccessCode();
            clientId = noticeSuccessClientId();
        } else {
            messageContent = messageRequired.type().getFailedCode();
            clientId = noticeFailedClientId();
        }
        NoticeTarget target = new NoticeTarget();
        target.setSeverity(severity);
        target.setSummary(MessageUtil.getMessageSource(StrUtil.addPrefixIfNot(messageTitle, prefix)));
        target.setDetail(MessageUtil.getMessageSource(StrUtil.addPrefixIfNot(messageContent, prefix)));
        target.setClientId(StrUtil.emptyToDefault(messageRequired.clientId(), clientId));
        return target;
    }

}
